<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 头部警告区 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      ></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col :span="3">
            <span>
            请选择商品分类:
            </span>
            </el-col>
        <el-col :span="5">
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="cateChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <!-- 这个位置是通过传递activeName来动态传递参数，从而请求数据 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDataDialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input_new_tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeData(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDataDialogVisible = true"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" style="width: 100%" border stripe>
            <!-- 展开行 -->
               <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input_new_tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 修改按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeData(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDataDialogVisible"
      width="50%"
      @close="addDataDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="addDataForm"
        :rules="addDataFormRules"
        ref="addDataFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addDataForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDataDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDataDialogVisible"
      width="50%"
      @close="editDataDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form
        :model="editDataForm"
        :rules="editDataFormRules"
        ref="editDataFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editDataForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDataDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      cateList: [],
      //指定级联选择器的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: false,
        expandTrigger: 'hover',
      },
      selectedCateKeys: [],
      //活跃的标签名称
      activeName: 'many',
      //动态参数
      manyTableData: [],
      //静态属性
      onlyTableData: [],
      //添加参数的表单
      addDataDialogVisible: false,
      //添加参数的表单数据
      addDataForm: {
        attr_name: '',
      },
      //添加参数的表单数据验证规则
      addDataFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
      editDataDialogVisible: false,
      //修改参数的表单数据
      editDataForm: {
        attr_name: '',
      },
      //修改参数的表单数据验证规则
      editDataFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
      //控制按钮和文本框的隐藏显示
      inputVisible: false,
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.cateList = res.data
    },
    //tabs上的点击事件
    handleTabClick() {
      this.getParamsData()
    },
    //级联上的change事件 选择框变化的时候，会触发这个函数
    async cateChange() {
      this.getParamsData()
    },
    async getParamsData() {
      //证明选中不是三级分类 直接清空数据
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData=[]
        this.onlyTableData=[]
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        //控制文本框的显示与隐藏
        item.inputVisible = false
        //文本框输入的值
        item.inputValue = ''
      })
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      if (this.activeName === 'many') {
        this.manyTableData = res.data
        console.log(this.manyTableData)
      } else {
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    addDataDialogClosed() {
      this.$refs.addDataFormRef.resetFields()
    },
    // 点击按钮，确认参数
    addData() {
      this.$refs.addDataFormRef.validate(async (valid) => {
        if (!valid) return
        //发起添加用户的网络请求
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addDataForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败')
        }
        //隐藏添加用户的对话框
        this.addDataDialogVisible = false
        //重新获取用户列表数据
        this.getParamsData()
        this.$message.success('添加参数成功')
      })
    },
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      this.editDataForm = res.data
      this.editDataDialogVisible = true
    },
    editDataDialogClosed() {
      this.$refs.editDataFormRef.resetFields()
    },
    //点击按钮，修改参数信息
    editData() {
      this.$refs.editDataFormRef.validate(async (valid) => {
        if (!valid) return
        //发起添加用户的网络请求
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editDataForm.attr_id}`,
          {
            attr_name: this.editDataForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        //隐藏添加用户的对话框
        this.editDataDialogVisible = false
        //重新获取用户列表数据
        this.getParamsData()
        this.$message.success('修改参数成功')
      })
    },
    async removeData(attr_id) {
      //使用element-ui的控件方法
      const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //如果用户确认删除，则返回字符串confirm
      //如果用户取消了删除，则返回的字符串为cancel
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getParamsData()
    },
    //文本框按下或失去焦点都会被触发的函数
    async handleInputConfirm(row) {
        //去除空格之后长度为零
        if(row.inputValue.trim().length===0){
            row.inputValue=""
            row.inputVisible=false
            return
        }
        //如果没有return就要做后续处理
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue=""
        row.inputVisible=false
        this.saveAttrVal(row)
    },
    async saveAttrVal(row){
         const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${row.attr_id}`,
          {
            attr_name: row.attr_name,
            attr_sel: row.attr_sel,
            attr_vals:row.attr_vals.join(',')
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败')
        }
        this.$message.success('修改参数成功')
    },
    //点击按钮，展示文本输入框
    showInput(row) {
      //通过row把这一行的所有数据传过来，找到其中的自定义属性inputVisible设置为true
      row.inputVisible = true
      //$nextTick方法的作用，就是当页面上的元素被重新渲染之后，才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleClose(i,row){
        //修改原数组
        row.attr_vals.splice(i,1)
        //重新请求数据
        this.saveAttrVal(row)
    }
  },
  computed: {
    isBtnDisabled() {
      //如果按钮需要被禁用，则返回true，否则返回false
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
  span{
      line-height: 40px;
  }
}
.input_new_tag {
  width: 120px;
}
</style>